const router = require('koa-router')()
const upload = require('../upload')
const mongoose = require('mongoose')
const statsfn = require('../lib/statsfn')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')

router.prefix('/images')

router.post('/',upload.single('imgfile'),async function(ctx) {
    if( ctx.session.nickname === undefined){
        ctx.redirect('/')
    }else{
        const {title, description} = ctx.req.body
        const {originalname, mimetype, filename: diskfilename} = ctx.req.file
        //图片上传者的昵称
        const nickname = ctx.session.nickname 
        const doc = await Image.create({
            title, description, originalname, mimetype, diskfilename, nickname
        })
        ctx.redirect('/')
    }
})

router.get('/:imageid',async ctx => {
    const doc = await Image.findByIdAndUpdate(
        ctx.params.imageid,
        {$inc: {visit: 1}},
        {new: true}
    )
    doc.stats = await statsfn()
    doc.comments = await Comment
        .find({image: ctx.params.imageid})
        .sort({createdAt: -1})
    if(doc){
        await ctx.render('show',doc)
    }
})

router.post('/likes/:imageid',async ctx => {
    const doc = await Image.findByIdAndUpdate(
        ctx.params.imageid,
        {$inc: {likes: 1}},
        {new: true}
    )
    ctx.body = {
        doc
    }
})
module.exports = router